package com.cy.sca.api.aspect;


import com.cy.sca.api.feign.RemoteNoticeService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class LogAspect {
    //*门面模式*
    private static final Logger log =
            LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(com.cy.sca.api.annotation.RequiredLog)")
    public void doLog(){

    }
    @Around("doLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
        Map<String,Object> logInfo = new HashMap<>();

        String className = joinPoint.getTarget().getClass().getName();
        logInfo.put("targetClass", className);//classname

        Signature signature = joinPoint.getSignature();
        String methodName = signature.getName();//methodName
        Object args[] = joinPoint.getArgs();//args
        String JsonArgs = new ObjectMapper().writeValueAsString(args);//toJson
//        System.out.println("methodName = " + methodName);
        logInfo.put("targetMethod", methodName);
//        System.out.println("JsonArgs = " + JsonArgs);
        logInfo.put("params", JsonArgs);
        long t1 = System.currentTimeMillis();
//        System.out.println("start = " + t1);
        try {
            Object result = joinPoint.proceed();//执行
            long t2 = System.currentTimeMillis();
            long time = t2 - t1;
            logInfo.put("status", 1);
            logInfo.put("usedTime", time);
//            System.out.println("end = " + t2);
            return result;
        }catch (Throwable e){
            long t3 = System.currentTimeMillis();
            long time = t3 - t1;
            logInfo.put("status", 0);
            logInfo.put("usedTime", time);
            logInfo.put("errorMsg", e.getMessage());
//            System.out.println("error = " + t3);
            throw e;
        }finally {
            log.info("operation log{}",logInfo.toString());
            //将logInfo发送给日志记录服务
            remoteNoticeService.doLoginInfo(logInfo);
        }
    }
    @Autowired
    private RemoteNoticeService remoteNoticeService;
}
